var CONTEXT = 'http://' + document.domain + '/MarinaSaoPedro';
//var CONTEXT = 'http://' + document.domain;

function showBox(content, callback){
    var html = [];
    var c = 0;
    html[c++] = '<div id="box" class="box">';
    html[c++] = content;
    html[c++] = '</div>';
    html[c++] = '<div id="bgBox" class="bg-box"></div>';
    $('body').append(html.join(''));
            
    var largura = $(window).width();
    var altura = $(document).height();
            
    var larguraBox = parseInt($('#box').css('width'));
    var alturaBox = parseInt($('#box').css('height'));
            
    $('#bgBox').css('width', largura);
    $('#bgBox').css('height', altura);
            
    $('#box').css('margin-left', (largura/2) - (larguraBox/2));
    $('#box').css('margin-top', ($(window).height()/2) - (alturaBox/2));
    
    $(window).scrollTop(0);
            
    $('#bgBox').fadeIn(300);
    $('#box').fadeIn(300);
    
    if(callback){
        callback();   
    }
}

function showBoxTextArea(referencia, texto){
    var html = [];
    var c = 0;
    
    html[c++] = '<div class="title"><label>Editor de Textos RRA 1.0</label></div>';
    html[c++] = '<span title="<h2></h2>" class="botao-edicao" onclick="controlTagInTextArea(\'conteudo\',\'h2\')">Título Grande</span>';
    html[c++] = '<span title="<h3></h3>" class="botao-edicao" onclick="controlTagInTextArea(\'conteudo\',\'h3\')">Título Médio</span>';
    html[c++] = '<span title="<b></b>" class="botao-edicao" onclick="controlTagInTextArea(\'conteudo\',\'b\')">Negrito</span>';
    html[c++] = '<span title="<i></i>" class="botao-edicao" onclick="controlTagInTextArea(\'conteudo\',\'i\')">Itálido</span>';
    html[c++] = '<span title="Remover todas tags no texto" class="botao-edicao" onclick="resetarTags(\'conteudo\')">Resetar</span>';
    html[c++] = '<textarea id="conteudo" style="width: 800px" rows="20">' + texto + '</textarea>';
    html[c++] = '<span class="botao-verde" onclick="atualizarConteudo(\'' + referencia + '\')">salvar</span>';
    html[c++] = '<span class="botao-vermelho" onclick="hideBox(true)">cancelar</span>';
    
    showBox(html.join(''), function(){
        $('#conteudo').focus();
    });
}

function controlTagInTextArea(id, tag){ 
    var textarea = document.getElementById(id); 
    var len = textarea.value.length; 
    var start = textarea.selectionStart; 
    var end = textarea.selectionEnd; 
    if(start != end){
        var newString = textarea.value.substring(start, end); 
        if(newString.indexOf('<' + tag + '>') > -1){
            newString = newString.replace('</' + tag + '>', '');
            newString = newString.replace('<' + tag + '>', '');
        }else{
            newString = '<' + tag +'>' + newString + '</' + tag + '>'; 
        }
        textarea.value =  textarea.value.substring(0,start) + newString + 
        textarea.value.substring(end,len);   
    }
}

function resetarTags(id){
    var tags = ['</h2>', '<h2>', '</h3>', '<h3>', '</b>', '<b>', '</i>', '<i>']
    var textarea = document.getElementById(id); 
    var newString = textarea.value;
    
    for(var i = 0; i < tags.length; i++){
        newString = newString.replace(tags[i], '', 'g');   
    }
    
    textarea.value = newString;
}

function showBoxCarregando(texto){
    var html = '<img src="' + CONTEXT + '/_recursos/imagens/carregando.gif"/>';
    html += '<h3>' + texto + '</h3>';
    showBox(html);
}

function hideBox(hideBg){
    if(hideBg){
        $('#bgBox').fadeOut(300, function(){
            $('#bgBox').remove(); 
        });   
    }
    $('#box').fadeOut(300, function(){
        $('#box').remove(); 
    });
}

function hideBoxNow(hideBg){
    if(hideBg){
        $('#bgBox').hide();
        $('#bgBox').remove(); 
    }
    
    $('#box').hide();
    $('#box').remove(); 
}

function teclaEnter(event, funcao){
    if(event.keyCode == 13){
        funcao();
    }
}

function atualizarConteudo(referencia){
    var conteudo = $('#conteudo').val();
    hideBoxNow(true);
    showBoxCarregando('Atualizando...');
    $.ajax({
        type:'POST',
        url:CONTEXT + '/admin/classes/Controler.php',
        data:{
            classe:'Pagina', 
            metodo: 'atualizar',
            conteudo: conteudo,
            referencia: referencia
        },
        success: function(){
            location.reload();
        },
        error: function(data){
            hideBoxNow(true);
            alert(data.statusText);
        }
    });
    
}

function showConteudo(e){
    showBoxTextArea(e.id, unescapeHtml(e.innerHTML));
}

function unescapeHtml(string){
    string = string.replace(/<br>/gi, "");
    string = string.replace(/&nbsp;/gi, "");
    return $.trim(string);
}

function showRenomearPasta(pasta){
    var desc = prompt("Digite o novo nome da galeria " + pasta + ":");
    if(desc == null){
        return;   
    }
    
    renomearPasta(pasta, desc);
}

function criarPasta(nome){
    showBoxCarregando('Criando...');
    $.ajax({
        type:'POST',
        url:CONTEXT + '/admin/classes/Controler.php',
        data:{
            classe:'Diretorio', 
            metodo: 'criar',
            PASTA: nome
        },
        success: function(){
            location.reload();
        },
        error: function(data){
            hideBoxNow(true);
            alert(data.statusText);
        }
    });
}

function deletarPasta(nome){
    if(!confirm('Deseja realmente remover essa galeria?')){
        return;
    }
    showBoxCarregando('Deletando...');
    $.ajax({
        type:'POST',
        url:CONTEXT + '/admin/classes/Controler.php',
        data:{
            classe:'Diretorio', 
            metodo: 'deletar',
            PASTA: nome
        },
        success: function(){
            location.reload();
        },
        error: function(data){
            hideBoxNow(true);
            alert(data.statusText);
        }
    });
}
function renomearPasta(pasta, nome){
    showBoxCarregando('Renomeando...');
    $.ajax({
        type:'POST',
        url:CONTEXT + '/admin/classes/Controler.php',
        data:{
            classe:'Diretorio', 
            metodo: 'renomear',
            PASTA: pasta,
            NOME: nome
        },
        success: function(){
            location.reload();
        },
        error: function(data){
            hideBoxNow(true);
            alert(data.statusText);
        }
    });
}

function getSelectedText() {
    if(window.getSelection) {
        return window.getSelection(); 
    }else if(document.getSelection) { 
        return document.getSelection(); 
    }else {
        var selection = document.selection && document.selection.createRange();
        if(selection.text) { 
            return selection.text; 
        }
        return false;
    }
    return false;
}

function redirecionar(pagina){
    window.location.href = pagina;
}

function showLogin(){
    var html = [];
    var c = 0;
    html[c++] = '<div id="boxLogin" class="box-login">';
    html[c++] = '   <div class="box-title">';
    html[c++] = '    <label>Acesso Restrito</label>';
    html[c++] = '    <span title="Fechar" onclick="hideBoxNow(true);">x</span>';
    html[c++] = '   </div>';
    html[c++] = '   <div class="box-conteudo">';
    html[c++] = '       <br/>';
    html[c++] = '       <label for"usuario">Usuário</label>';
    html[c++] = '       <br/>';
    html[c++] = '       <input id="usuario" type="text"/>';
    html[c++] = '       <br/>';
    html[c++] = '       <label for="senha">Senha</label>';
    html[c++] = '       <br/>';
    html[c++] = '       <input onkeypress="teclaEnter(event, logar)" id="senha" type="password"/>';
    html[c++] = '       <br/>';
    html[c++] = '       <span onclick="logar()" class="botao-azul">Entrar</span>';
    html[c++] = '   </div>';
    html[c++] = '</div>';
    showBox(html.join(''), function(){
        $('#usuario').focus()
    });
}


function logar(){
    var u = $('#usuario').val();
    var s = $('#senha').val();
    if(!u){
        //TODO - tratar com label
        hideBox(true);
        alert('Digite o usuário');
        $('#usuario').focus();
        return;
    }
    if(!s){
        //TODO - tratar com label
        hideBox(true);
        alert('Digite a senha');
        $('#senha').focus();
        return;
    }
    
    hideBoxNow(true);
    showBoxCarregando('Autenticando Usuário...');
    $.post(CONTEXT + '/admin/classes/Controler.php', {
        classe:'Usuario', 
        metodo:'login',
        usuario: u,
        senha: s
    }, function(resp){
        if(resp == 1){
            window.location.href = CONTEXT + '/admin/aulas_praticas.php';
        }else{
            hideBoxNow();
            showLogin();
            alert('Usuário ou senha inválidos')
        }
    },'text');
}

function logoff(){
    showBoxCarregando("Fazendo Logoff...");
    $.ajax({
        type:'POST',
        url: CONTEXT + '/admin/classes/Controler.php',
        data:{
            classe:'Usuario', 
            metodo:'logoff'
        },
        success: function(){
            window.location.href = CONTEXT ;
        },
        error: function(req){
            hideBox(true);
            alert(req);
        }
    });
}

function getParametro(name, url){
    url = url.split('?')[1];
    var itens = url.split("&");
    for(var i = 0; i< itens.length; i++)
    {
        if(itens[i].match(name))
        {
            return decodeURIComponent(itens[i].replace(name + "=", ""));
        }
    }
    return null;
}